import React, {useRef, useState} from 'react';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  AddShippingPlan,
  DeleteShippingPlan,
  DeleteShippingPlanDetail,
  ModifyShippingPlan,
  ShippingPlanVO
} from "@/apiNew/shippingPlan";
import {ADD_ITEM_FLAG, isAddItem, isSuccessRes} from "@/types/common";
import {Card, notification, Popconfirm, Tooltip, Button} from "antd";
import {MockQueryShippingPlan} from "@/views/regulation/logisticsReplaceRule/mockQueryData";
import {ShippingDetailsComp} from "@/views/regulation/logisticsReplaceRule/ShippingDetails";
import {paramsDataFormat} from "@/types/format";
import {PlusOutlined, QuestionCircleOutlined} from "@ant-design/icons";

export const LogisticsReplaceRuleReact = () => {


  const columns: ProColumns<ShippingPlanVO>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      title: '序号',
    },
    {
      title: '物流替代规则名称', dataIndex: 'Name',
      formItemProps: (form) => {
        return {
          rules: [{required: true, message: '此项为必填项'}],
        };
      },
      width: '30%',
      copyable: true,
    },
    {
      title: (
        <>
          创建时间
          <Tooltip placement="top" title="😉😊🎉🐱‍👤👀😃😢✔">
            <QuestionCircleOutlined style={{marginLeft: 4}}/>
          </Tooltip>
        </>
      ), dataIndex: 'OperateTime', editable: false, valueType: 'date',
      sorter: (a: any, b: any) => a.OperateTime - b.OperateTime,

    },
    {title: '创建人', dataIndex: 'OperateUserName', editable: false},

    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={(e) => {
            e.stopPropagation()
            action.startEditable?.(record.ShippingPlanId);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          title="Are you sure to delete this plan?"
          onConfirm={async () => {
            // setDataSource(dataSource.filter((item) => item.ShippingPlanId !== record.ShippingPlanId));
            try {
              const responseData = await DeleteShippingPlan(record.ShippingPlanId);
              if (isSuccessRes(responseData)) {
                notification.success({message: '删除数据成功',})
                actionRef.current?.reload();
              }
            } catch (e) {
              console.log(e)
            }
          }}
          okText="Yes"
          cancelText="No"
        >
          <a href="#" onClick={(event) => {
            event?.stopPropagation()
          }}>删除</a>
        </Popconfirm>,

      ],
    },
  ];

  const actionRef = useRef<ActionType>();

  return (
    <>
      <ProTable<ShippingPlanVO>
        pagination={{
          showSizeChanger: true,
        }}

        toolBarRender={() => [
          <Button onClick={() => {
            const shippingFactory = () => {
              return {
                ShippingPlanId: ADD_ITEM_FLAG,
                Name: '',
                OperateTime: '',
                OperateUserId: 0,
                OperateUserName: '',
                ShippingPlanDetails: [],
              }
            }

            actionRef.current?.addEditRecord(shippingFactory())

          }} key="button" icon={<PlusOutlined/>} type="primary">
            新建
          </Button>,
        ]}

        actionRef={actionRef}
        rowKey="ShippingPlanId"
        headerTitle="物流替代规则"

        // toolBarRender={() => []}

        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}

        expandable={{
          expandedRowRender: record => {
            //    const cacheShippingRef  = useRef()
            console.log(record)
            return <ShippingDetailsComp actionRef={actionRef} shippingDetails={record}/>
          },
          rowExpandable: (record) => {
            return record.ShippingPlanId !== ADD_ITEM_FLAG
          }
        }}

        columns={columns}
        request={async ({current, pageSize, Name: PlanName, ...restParams}: any) => {
          try {
            console.log(restParams)
            const responseData = await MockQueryShippingPlan({
              // const responseData = await QueryShippingPlan({
              PlanName,
              // "STTime": "2021-01-26T01:17:48.458Z",
              // "EndTime": "2021-01-26T01:17:48.458Z",
              // "ShopId": 0,
              "PageSize": pageSize,
              "PageIndex": current
            });

            if (isSuccessRes(responseData)) {
              const {Result: {TotalNum: total, Items}} = responseData;
              return {
                total,
                data: Items,
                success: true
              }
            }
            return {
              success: false,
              data: [],
            }
          } catch (e) {
            console.log(e)
            return {
              success: false,
              data: [],
            }
          }
        }}
        editable={{
          onSave: async (key, {index, ...row}, newLine) => {
            console.log(key, row, newLine, isAddItem(key))
            const isEditStatus = !isAddItem(key)
            try {
              const responseData = await (isEditStatus ? ModifyShippingPlan : ModifyShippingPlan)({
                ...{
                  ...row as ShippingPlanVO,
                  ...(() => (isAddItem(key) ? {
                    ShippingPlanId: 0
                  } : {}))()
                },
                ShippingPlanDetails: row.ShippingPlanDetails.map(details => {
                  return paramsDataFormat(details, ['StartTime', 'EndTime'])
                })
              } as any)
              if (isSuccessRes(responseData)) {
                actionRef.current?.reload();
                notification.success({message: `${isEditStatus ? '修改' : '新增'}数据成功`,})
                return true
              }
              return false
            } catch (e) {
              console.log(e)
              notification.warn({message: `${isEditStatus ? '修改' : '新增'}数据失败`,})
              return false
            }
          },
        }}
      />

    </>
  );
}
